package cn.tedu.smartos.family_user.service.impl;

import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.family_user.mapper.ElderlyBindMapper;
import cn.tedu.smartos.family_user.pojo.dto.ElderlyBindParam;
import cn.tedu.smartos.family_user.pojo.entity.ElderlyInfo;
import cn.tedu.smartos.family_user.pojo.entity.FamilyElderlyRelation;
import cn.tedu.smartos.family_user.pojo.vo.BoundElderlyVO;
import cn.tedu.smartos.family_user.service.ElderlyBindService;
import lombok.extern.slf4j.Slf4j;
import cn.tedu.smartos.baseuser.pojo.entity.User;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 老人绑定服务实现类
 */
@Slf4j
@Service
public class ElderlyBindServiceImpl implements ElderlyBindService {
    @Autowired
    private ElderlyBindMapper elderlyBindMapper;

    /**
     * 绑定老人信息
     * 1. 验证家属用户存在且类型为家属(2)
     * 2. 检查老人手机号是否已注册
     * 3. 未注册则创建老人用户和健康信息
     * 4. 检查绑定关系是否已存在
     * 5. 创建家属-老人关系
     *
     * @param bindParam 绑定参数对象
     * @return 绑定老人的用户ID
     */
    @Transactional
    @Override
    public Long bindElderly(ElderlyBindParam bindParam) {
        // 1. 检查家属用户是否存在
        User familyUser = elderlyBindMapper.selectUserById(bindParam.getFamilyUserId());
        if (familyUser == null || !familyUser.getUserType().equals(2)) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT, "家属用户不存在");
        }

        // 2. 检查老人是否已注册
        User elderlyUser = elderlyBindMapper.selectUserByPhone(bindParam.getPhone());
        Long elderlyUserId;

        if (elderlyUser == null) {
            // 3. 创建老人用户
            elderlyUser = new User();
            BeanUtils.copyProperties(bindParam, elderlyUser);

// 系统生成字段
            elderlyUser.setUserType(1);
            elderlyUser.setStatus(1);
            elderlyUser.setIsDeleted(0);
            elderlyUser.setPermission("0");
            elderlyUser.setUsername(bindParam.getPhone()); // 手机号即账号
            elderlyUser.setPassword(bindParam.getPassword()); // 使用用户输入的密码
            elderlyUser.setRegisterTime(new Date());
            elderlyUser.setUpdateTime(new Date());

// 空字段兜底
            if(elderlyUser.getFaceToken() == null)
                elderlyUser.setFaceToken("");
            if(elderlyUser.getIdCard() == null)
                elderlyUser.setIdCard("");

            elderlyBindMapper.insertUser(elderlyUser);
            elderlyUserId = elderlyUser.getUserId();

            // 4. 创建老人健康信息
            ElderlyInfo elderlyInfo = new ElderlyInfo();
            BeanUtils.copyProperties(bindParam, elderlyInfo);
            elderlyInfo.setUserId(elderlyUserId);
            elderlyBindMapper.insertElderlyInfo(elderlyInfo);
        } else {
            elderlyUserId = elderlyUser.getUserId();
            // 检查是否已经是该老人的家属
            if (elderlyBindMapper.relationExists(bindParam.getFamilyUserId(), elderlyUserId) > 0) {
                throw new ServiceException(StatusCode.FAILED, "该老人已被绑定");
            }
        }

        // 5. 创建绑定关系
        FamilyElderlyRelation relation = new FamilyElderlyRelation();
        relation.setFamilyUserId(bindParam.getFamilyUserId());
        relation.setElderlyUserId(elderlyUserId);
        relation.setRelationType(bindParam.getRelationType());
        relation.setIsPrimary(bindParam.getIsPrimary());
        relation.setCreateTime(new Date());

        elderlyBindMapper.insertRelation(relation);

        return elderlyUserId;
    }
    @Override
    public boolean isValidRelation(Long familyUserId, Long elderlyUserId) {
        return elderlyBindMapper.relationExists(familyUserId, elderlyUserId) > 0;
    }
    @Override
    public List<Long> getFamilyUserIdsByElderlyId(Long elderlyUserId) {
        return elderlyBindMapper.selectFamilyUserIdsByElderlyId(elderlyUserId);
    }
    @Override
    public List<BoundElderlyVO> getBoundElderly(Long familyUserId) {
        List<BoundElderlyVO> list = elderlyBindMapper.selectBoundElderlyByFamilyUserId(familyUserId);
        list.forEach(vo -> {
            if (vo.getAvatarUrl() != null && !vo.getAvatarUrl().startsWith("http")) {
                vo.setAvatarUrl("http://localhost:8080/" + vo.getAvatarUrl());
            }
        });
        return list;
    }
    @Override
    @Transactional
    public void unbind(Long familyUserId, Long elderlyUserId) {
        if (!isValidRelation(familyUserId, elderlyUserId)) {
            throw new ServiceException(StatusCode.FAILED, "绑定关系不存在");
        }
        elderlyBindMapper.deleteRelation(familyUserId, elderlyUserId);
    }

    @Override
    public List<BoundElderlyVO> getBoundElderly(Long familyUserId,
                                                String relationType,
                                                String realName) {
        return elderlyBindMapper.selectBoundElderlyByCondition(familyUserId, relationType, realName);
    }
}
